package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.constant.CartListConstant;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.ItemCatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
@org.springframework.stereotype.Service
public class CartServiceImpl implements CartService {

    private static final Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);

    @Reference
    private ItemCatService itemCatService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Cart> insertCartList(List<Cart> carts,Long itemId, Integer num) {
        //1、根据itemId查询SKU商品信息
        TbItem item = itemCatService.getItemByItemId(itemId);
        //2、获取商家id
        String sellerId = item.getSellerId();
        //3、根据商家的id 去carts（原来的购物车）查询有没有该商家
        Cart cart = queryCartBySellerId(carts, sellerId);
        //4、如果购物车列表里没有该商家的id
        if (null == cart){
            //4.1 创建新的购物车对象
            cart = new Cart();
            //组装购物车信息
            cart.setSellerId(sellerId);
            cart.setSellerName(item.getSeller());
            TbOrderItem tbOrderItem = creatOrderItem(item,num);
            List<TbOrderItem> tbOrderItemList = new ArrayList<>();
            tbOrderItemList.add(tbOrderItem);
            cart.setTbOrderItemList(tbOrderItemList);
            //4.2 将新建的购物车对象添加到购物车列表中
            carts.add(cart);
            logger.info("执行成功");
            return carts;
        }else {
            //5、如果购物车列表中已经有该商家的id
            //6、查询购物车的列表，判断是否存在现在要添加的商品
            List<TbOrderItem> tbOrderItemList = cart.getTbOrderItemList();
            TbOrderItem tbOrderItem = queryCartBySellerId(tbOrderItemList, itemId);
            if (null == tbOrderItem){
                //6.1 如果不存在 新增购物车明细
                tbOrderItem = creatOrderItem(item,num);
                cart.getTbOrderItemList().add(tbOrderItem);
            }else {
                //6.2 如果存在 在原有的购物车明细上修改商品的数量和总价格
                tbOrderItem.setNum(tbOrderItem.getNum() + num);
                tbOrderItem.setTotalFee(new BigDecimal(tbOrderItem.getNum() * tbOrderItem.getPrice().doubleValue()));
                //如果操作后num为0，我们需要将这个购物车 明细从列表中删除
                if (tbOrderItem.getNum() <= 0){
                    tbOrderItemList.remove(tbOrderItem);
                }
                //如果移除之后购物车列表空了，那么就将这个购物车移除掉
                if (cart.getTbOrderItemList().size() == 0){
                    carts.remove(cart);
                }
            }
            logger.info("执行成功");
        }
        return carts;
    }

    //封装方法 根据sellerId 查询cart
    private Cart queryCartBySellerId(List<Cart> carts,String sellerId){
        return carts.stream().filter(c -> Objects.equals(c.getSellerId(),sellerId)).findFirst().orElse(null);
    }

    //提取组装购物车明细
    private TbOrderItem creatOrderItem(TbItem item, Integer num){
        TbOrderItem tbOrderItem = new TbOrderItem();
        tbOrderItem.setItemId(item.getId());
        tbOrderItem.setNum(num);
        tbOrderItem.setPicPath(item.getImage());
        tbOrderItem.setPrice(item.getPrice());
        tbOrderItem.setTitle(item.getTitle());
        tbOrderItem.setGoodsId(item.getGoodsId());
        tbOrderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * num));
        return tbOrderItem;
    }

    //封装方法 根据sellerId 查询cart
    private TbOrderItem queryCartBySellerId(List<TbOrderItem> tbOrderItemList,Long itemId){
        return tbOrderItemList.stream().filter(o -> Objects.equals(o.getItemId(), itemId)).findFirst().orElse(null);
    }

    //将购物车中的数据保存到redis中
    @Override
    public void insertCartListToRedis(String userName, List<Cart> carts) {
        redisTemplate.boundHashOps(CartListConstant.CAR_LIST_KEY).put(userName,carts);
        logger.info("执行成功");
    }

    //从redis中获取到购物车数据
    @Override
    public List<Cart> findCartFormRedis(String userName) {
        logger.info("执行成功");
        return Optional.ofNullable((List<Cart>) redisTemplate.boundHashOps(CartListConstant.CAR_LIST_KEY).get(userName)).orElse(new ArrayList<>());
    }

    //合并购物车
    @Override
    public List<Cart> mergeCartList(List<Cart> carts1, List<Cart> carts2) {
        for (Cart cart : carts1) {
            for (TbOrderItem tbOrderItem : cart.getTbOrderItemList()) {
                carts2 = insertCartList(carts2,tbOrderItem.getItemId(),tbOrderItem.getNum());
            }
        }
        return carts2;
    }
}
